package com.zhongshengnetwork.rightbe.lang.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.huantansheng.easyphotos.models.puzzle.Line;
import com.hys.utils.ImageUtils;
import com.lcodecore.tkrefreshlayout.OnAnimEndListener;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Des;
import com.zhongshengnetwork.rightbe.common.Filter.FilterTools;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TextUtil.DisplayUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.RoundBackChange;
import com.zhongshengnetwork.rightbe.common.customview.ShareDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.model.CustomFontModel;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;
import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class ShareActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private static final String AppShareUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe";
    private static final int REQUEST_PUBLISH = 10002;
    private static final int LANG_TYPE = 1119;
    private static final int REQUEST_LOCATION = 1211;//地理位置
    private static final int TAKE_PICTURE = 1212;//拍照
    private static final int SELECT_WZT = 1213;
    private static final int CHOOSE_PICTURE = 1214;//从相册选择
    private static final int FILTER_PICTURE = 1215; //图片滤镜
    private static final int REQUEST_PERMISSION = 10003;
    private static final int PHOTO_PICKER_REQUEST_CODE = 10004; //android 13从相册选择一张图片
    private static String imageFileName = "";//拍照图片名称
    private static String cropFilePath = "";

    private TopBarView topbar;

    //上图下文
    private ScrollView scrollview1;
    private LinearLayout img_share_layout;
    private ImageView header;
    private ImageView cover;
    private TextView text;
    private TextView from;
    private TextView from_tip;
    private LinearLayout bottom_layout;


    //上文下图
    private ScrollView scrollview2;
    private LinearLayout uptext_downimg_share_layout;
    private TextView up_text;
    private ImageView down_cover;
    private TextView uptext_downimg_from;
    private TextView uptext_downimg_from_tip;
    private LinearLayout uptext_downimg_bottom_layout;


    //全文
    private ScrollView scrollview3;
    private LinearLayout text_share_layout;
    private TextView full_text;
    private LinearLayout fulltext_bottom_layout;
    private TextView fulltext_from;
    private TextView fulltext_from_tip;

    private LangInfoModel langInfoModel;
    private int screenWidth = 0;

    private Bitmap shareBitmap = null;

    private String filePath = null;



    private int count = 0;

    private LinearLayout menu1;
    private ImageView icon1;
    private TextView text1;
    private LinearLayout menu2;
    private ImageView icon2;
    private TextView text2;
    /*
    private LinearLayout menu3;
    private ImageView icon3;
    private TextView text3;
    */
    private LinearLayout menu4;
    private ImageView icon4;
    private TextView text4;
    private LinearLayout menu5;
    private ImageView icon5;
    private TextView text5;
    /*
    private LinearLayout menu6;
    private ImageView icon6;
    private TextView text6;
    */
    private int selectMenuIndex = -1;

    //模板菜单
    private LinearLayout mouldmenu;
    private ImageView mouldselect1;
    private ImageView mouldselect2;
    private ImageView mouldselect3;
    private ImageView mouldselect4;
    private ImageView mouldselect5;
    private RelativeLayout writer_layout;
    private RoundBackChange whitebg;
    private ImageView writer_header;
    private TextView writer_nickname;
    private int selectMouldIndex = 0;

    //图片菜单
    private HorizontalScrollView tpmenu;
    private LinearLayout tpItemContainer;
    private int selectTPIndex = 3;
    private TextView selectTPTextView;
    private boolean isOriginalTP = false;
    private float bitmapScale = 17.0f/30.0f;
    private Bitmap originalBitmap = null;
    private Bitmap selectBitmap = null;
    private String imgUrl = "";
    private String tpmenus[] = new String[]{"xiangce", "paizhao", "原图", "30:17", "1:1", "2:1", "3:2",
            "16:9", "4:3", "2:3", "3:4"};
    private TextView originalTPTextView = null;

    //排版菜单
    private HorizontalScrollView pbmenu;
    private LinearLayout pbItemContainer;
    private String pbmenus[] = new String[]{"A+", "A-", "标准", "小", "中", "大"};
    private int pbiconmenus[] = new int[]{R.drawable.zuoqi, R.drawable.juzhong, R.drawable.youqi, R.drawable.liangduanduiqi, R.drawable.addbj, R.drawable.bj};
    private CustomFontModel customFontModel = null;

    //颜色菜单
    private String colormenus[] = new String[]{"#808069", "#FFFFFF", "#F0F0F0", "#292421", "#FFFF00", "#A020F0", "#C0C0C0", "#B0E0E6", "#00FFFF"
    , "#FF4500", "#FF00FF", "#FF6347", "#872657", "#FFC0CB", "#B03060", "#9C661F", "#E3170D", "#FF7F50", "#B22222", "#00C78C", "#3D59AB", "#1E90FF", "#385E0F", "#00C957", "#FF6100", "#FF8000"};
    private LinearLayout colormenu;
    private HorizontalScrollView textcolormenu;
    private LinearLayout textcolorItemContainer;
    private HorizontalScrollView bgcolormenu;
    private LinearLayout bgcolorItemContainer;

    //水印菜单
    private HorizontalScrollView symenu;
    private LinearLayout syItemContainer;
    private int symenus[] = new int[]{R.drawable.shuiyin1, R.drawable.shuiyin2};

    private boolean shareImg = true;
    private ImageView shareimg;
    private boolean isEditTP = false; //是否编辑过图文

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.getRightView().setImageResource(R.drawable.shareicon);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more(v);
            }
        });
        topbar.setClickListener(this);
        topbar.getTitleView().setText("图文分享");

        RelativeLayout share_layout = (RelativeLayout) findViewById(R.id.share_layout);
        share_layout.setClickable(true);
        share_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(-1);
            }
        });

        shareimg = (ImageView) findViewById(R.id.shareimg);
        shareimg.setClickable(true);
        shareimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareImg = true;
                showShare();
            }
        });

        langInfoModel =  (LangInfoModel) getIntent().getSerializableExtra("model");

        customFontModel = new CustomFontModel();
        customFontModel.setFontColor("#000000");
        customFontModel.setBgColor("#FFFFFF");
        customFontModel.setTipColor("#C0C0C0");
        customFontModel.setFontSize(16);
        customFontModel.setFontUrl("");
        customFontModel.setGravity(Gravity.CENTER);
        customFontModel.setPadding(20);

        int width = ScreenUtils.getScreenWidth(ShareActivity.this);
        screenWidth = width-ScreenUtils.dip2px(ShareActivity.this, 30);

        scrollview1 = (ScrollView) findViewById(R.id.scrollview1);
        img_share_layout = (LinearLayout) findViewById(R.id.img_share_layout);
        bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
        header = (ImageView) findViewById(R.id.header);
        cover = (ImageView) findViewById(R.id.cover);
        ViewGroup.LayoutParams params = cover.getLayoutParams();
        params.width = screenWidth;
        params.height = Math.round(screenWidth / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO);
        cover.setLayoutParams(params);

        int h = Math.round(screenWidth / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO) - ScreenUtils.dip2px(ShareActivity.this, 10);
        params = header.getLayoutParams();
        params.width = h;
        params.height = h;
        header.setLayoutParams(params);

        //上文下图
        scrollview2 = (ScrollView) findViewById(R.id.scrollView2);
        uptext_downimg_share_layout = (LinearLayout) findViewById(R.id.uptext_downimg_share_layout);
        up_text = (TextView) findViewById(R.id.up_text);
        down_cover = (ImageView) findViewById(R.id.down_cover);
        uptext_downimg_from = (TextView) findViewById(R.id.uptext_downimg_from);
        uptext_downimg_bottom_layout = (LinearLayout) findViewById(R.id.uptext_downimg_bottom_layout);
        params = down_cover.getLayoutParams();
        params.width = screenWidth;
        params.height = Math.round(screenWidth / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO);
        down_cover.setLayoutParams(params);

        //全文
        scrollview3 = (ScrollView) findViewById(R.id.scrollView3);
        text_share_layout = (LinearLayout) findViewById(R.id.text_share_layout);
        full_text = (TextView) findViewById(R.id.full_text);
        fulltext_bottom_layout = (LinearLayout) findViewById(R.id.fulltext_bottom_layout);
        fulltext_from = (TextView) findViewById(R.id.fulltext_from);

        imgUrl = "";

        if(langInfoModel.getImglist() != null && langInfoModel.getImglist().size() > 0){
            imgUrl = langInfoModel.getImglist().get(0);
            header.setVisibility(View.INVISIBLE);
            cover.setVisibility(View.VISIBLE);
            selectMouldIndex = 0;
        }else {
            imgUrl = langInfoModel.getHeader();
            if (!CommonUtils.isEmpty(langInfoModel.getSmallIcon())){
                int index = CommonUtils.appearNumber(langInfoModel.getHeader(), langInfoModel.getSmallIcon());
                if (index > 0){
                    imgUrl = imgUrl.substring(0, index);
                }
            }
            header.setVisibility(View.VISIBLE);
            cover.setVisibility(View.INVISIBLE);
            selectMouldIndex = 1;
        }
        try{
            Glide.with(ShareActivity.this).load(imgUrl).
                    diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
        }catch (Exception e){
            LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
        }
        try{
            //diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            Glide.with(ShareActivity.this).load(imgUrl).transform(new CircleTransform(ShareActivity.this)).dontAnimate().into(header);
        }catch (Exception e){
            LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
        }
        try{
            Glide.with(ShareActivity.this).load(imgUrl).
                    diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(down_cover);
        }catch (Exception e){
            LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
        }

        header.setClickable(true);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageMenu();
            }
        });
        cover.setClickable(true);
        cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageMenu();
            }
        });
        down_cover.setClickable(true);
        down_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageMenu();
            }
        });

        text = (TextView) findViewById(R.id.text);
        text.setText(langInfoModel.getTitle());
        up_text.setText(langInfoModel.getTitle());
        full_text.setText(langInfoModel.getTitle());

        text.setTextColor(Color.parseColor(customFontModel.getFontColor()));
        up_text.setTextColor(Color.parseColor(customFontModel.getFontColor()));
        full_text.setTextColor(Color.parseColor(customFontModel.getFontColor()));

        text.setClickable(true);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(-1);
            }
        });
        up_text.setClickable(true);
        up_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(-1);
            }
        });
        full_text.setClickable(true);
        full_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(-1);
            }
        });

        from = (TextView) findViewById(R.id.from);
        from_tip = (TextView) findViewById(R.id.from_tip);
        uptext_downimg_from_tip = (TextView) findViewById(R.id.uptext_downimg_from_tip);
        fulltext_from_tip = (TextView) findViewById(R.id.fulltext_from_tip);
        if (langInfoModel.isOriginal() == true && !CommonUtils.isEmpty(langInfoModel.getWeijuid())){
            from.setText("微句号："+langInfoModel.getWeijuid());
            uptext_downimg_from.setText("微句号："+langInfoModel.getWeijuid());
            fulltext_from.setText("微句号："+langInfoModel.getWeijuid());
        }else {
            from_tip.setVisibility(View.GONE);
            uptext_downimg_from_tip.setVisibility(View.GONE);
            fulltext_from_tip.setVisibility(View.GONE);
        }

        menu1 = (LinearLayout) findViewById(R.id.menu1);
        menu1.setClickable(true);
        menu1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(0);
            }
        });
        icon1 = (ImageView) findViewById(R.id.icon1);
        text1 = (TextView) findViewById(R.id.text1);

        menu2 = (LinearLayout) findViewById(R.id.menu2);
        menu2.setClickable(true);
        menu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectMouldIndex == 3){
                    ToastUtil.show(ShareActivity.this, "亲，当前选择模板不支持图片更换哦~");
                    return;
                }
                onClickBottomMenu(1);
            }
        });
        icon2 = (ImageView) findViewById(R.id.icon2);
        text2 = (TextView) findViewById(R.id.text2);

        /*
        menu3 = (LinearLayout) findViewById(R.id.menu3);
        menu3.setClickable(true);
        menu3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(2);
            }
        });
        icon3 = (ImageView) findViewById(R.id.icon3);
        text3 = (TextView) findViewById(R.id.text3);
        */

        menu4 = (LinearLayout) findViewById(R.id.menu4);
        menu4.setClickable(true);
        menu4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(3);
            }
        });
        icon4 = (ImageView) findViewById(R.id.icon4);
        text4 = (TextView) findViewById(R.id.text4);

        menu5 = (LinearLayout) findViewById(R.id.menu5);
        menu5.setClickable(true);
        menu5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(4);
            }
        });
        icon5 = (ImageView) findViewById(R.id.icon5);
        text5 = (TextView) findViewById(R.id.text5);

        /*
        menu6 = (LinearLayout) findViewById(R.id.menu6);
        menu6.setClickable(true);
        menu6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickBottomMenu(5);
            }
        });
        icon6 = (ImageView) findViewById(R.id.icon6);
        text6 = (TextView) findViewById(R.id.text6);
        */

        //模板菜单
        mouldmenu = (LinearLayout) findViewById(R.id.mouldmenu);
        mouldselect1 = (ImageView) findViewById(R.id.mouldselect1);
        mouldselect2 = (ImageView) findViewById(R.id.mouldselect2);
        mouldselect3 = (ImageView) findViewById(R.id.mouldselect3);
        mouldselect4 = (ImageView) findViewById(R.id.mouldselect4);
        mouldselect5 = (ImageView) findViewById(R.id.mouldselect5);
        writer_layout = (RelativeLayout) findViewById(R.id.writer_layout);
        writer_nickname = (TextView) findViewById(R.id.writer_nickname);
        writer_header = (ImageView) findViewById(R.id.writer_header);
        whitebg = (RoundBackChange) findViewById(R.id.whitebg);
        try{
            String img = langInfoModel.getHeader();
            if (!CommonUtils.isEmpty(langInfoModel.getSmallIcon())){
                int index = CommonUtils.appearNumber(langInfoModel.getHeader(), langInfoModel.getSmallIcon());
                if (index > 0){
                    img = img.substring(0, index);
                }
            }
            Glide.with(ShareActivity.this).load(img).transform(new CircleTransform(ShareActivity.this)).dontAnimate().into(writer_header);
            writer_nickname.setText(langInfoModel.getNickname());
        }catch (Exception e){
            LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
        }
        RelativeLayout mould1 = (RelativeLayout) findViewById(R.id.mould1);
        mould1.setClickable(true);
        mould1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickMouldMenu(0);
            }
        });
        RelativeLayout mould2 = (RelativeLayout) findViewById(R.id.mould2);
        mould2.setClickable(true);
        mould2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickMouldMenu(1);
            }
        });
        RelativeLayout mould3 = (RelativeLayout) findViewById(R.id.mould3);
        mould3.setClickable(true);
        mould3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickMouldMenu(2);
            }
        });
        RelativeLayout mould4 = (RelativeLayout) findViewById(R.id.mould4);
        mould4.setClickable(true);
        mould4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickMouldMenu(3);
            }
        });
        RelativeLayout mould5 = (RelativeLayout) findViewById(R.id.mould5);
        mould5.setClickable(true);
        mould5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickMouldMenu(4);
            }
        });
        clickMouldMenu(selectMouldIndex);

        //图片菜单
        tpmenu = (HorizontalScrollView) findViewById(R.id.tpmenu);
        tpmenu.setHorizontalScrollBarEnabled(false);
        tpItemContainer = (LinearLayout) findViewById(R.id.tpItemContainer);
        bindTPMenu();

        //排版菜单
        pbmenu = (HorizontalScrollView) findViewById(R.id.pbmenu);
        pbmenu.setHorizontalScrollBarEnabled(false);
        pbItemContainer = (LinearLayout) findViewById(R.id.pbItemContainer);
        bindPBMenu();

        //颜色菜单
        colormenu = (LinearLayout) findViewById(R.id.colormenu);
        textcolormenu = (HorizontalScrollView) findViewById(R.id.textcolormenu);
        textcolormenu.setHorizontalScrollBarEnabled(false);
        textcolorItemContainer = (LinearLayout) findViewById(R.id.textcolorItemContainer);
        bindTextColorMenu();
        bgcolormenu = (HorizontalScrollView) findViewById(R.id.bgcolormenu);
        bgcolormenu.setHorizontalScrollBarEnabled(false);
        bgcolorItemContainer = (LinearLayout) findViewById(R.id.bgcolorItemContainer);
        bindBgColorMenu();

        //水印菜单
        symenu = (HorizontalScrollView) findViewById(R.id.symenu);
        symenu.setHorizontalScrollBarEnabled(false);
        syItemContainer = (LinearLayout) findViewById(R.id.syItemContainer);
        bindSYMenu();

        //showShare();
        try{
            Glide.with(ShareActivity.this).load(imgUrl).
                    diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(down_cover);
            //获取图片真正的宽高
            Glide.with(this)
                    .asBitmap()//强制Glide返回一个Bitmap对象
                    .load(imgUrl)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                            if (resource == null){
                                return;
                            }
                            int width = resource.getWidth();
                            int height = resource.getHeight();
                            bitmapScale = 1.0f*height/width;
                            originalBitmap = resource;
                            /*
                            if (originalTPTextView != null){
                                if(langInfoModel.getImglist() != null && langInfoModel.getImglist().size() > 0){
                                    if (bitmapScale <= 1.0f){//比例小于1:1的显示原图
                                        clickPicMenu(originalTPTextView);
                                    }

                                }
                            }
                            */
                            Log.e("TAG", "图片实际大小比例="+bitmapScale);
                        }
                    });
        }catch (Exception e){
            LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
        }

        updateTextView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(CommonUtils.isLogin() == true){
            if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean("sharetip", false) == false){
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean("sharetip", true);
                CustomDialog dialog = null;
                final CustomDialog.Builder builder = new CustomDialog.Builder(ShareActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("亲，点击底部菜单项，您可以选择分享模板、编辑图片、修改文字大小颜色哦~");
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void more(View view){
        onClickBottomMenu(-1);
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(ShareActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        PermissionUtils.isPictureNote(ShareActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                    if (ActivityCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 申请权限
                        ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                        return;
                    }

                    final List<String> menu = new ArrayList<String>();
                    menu.add("分享图文");
                    menu.add("保存图文");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ShareActivity.this)
                            .builder()
                            .setTitle("")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String m : menu){
                        actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which == 2){
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                            && ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                        ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                REQUEST_PERMISSION);
                                        //ToastUtil.show(ShareActivity.this,"亲，请开启应用对SD卡的读写权限");
                                        return;
                                    }
                                    final Bitmap bitmap = viewConversionBitmap();
                                    if (bitmap != null){
                                        CommonUtils.saveBmp2Gallery(bitmap, System.currentTimeMillis()+"");
                                    }
                                }else if (which == 1){
                                    shareImg = true;
                                    showShare();
                                }else if (which == 3){
                                    shareImg = false;
                                    showShare();
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();
                }
            }
        });

    }

    private Bitmap viewConversionBitmap() {

        View v = null;
        if (scrollview1.getVisibility() == View.VISIBLE){
            v = img_share_layout;
        }else if (scrollview2.getVisibility() == View.VISIBLE){
            v = uptext_downimg_share_layout;
        }else if (scrollview3.getVisibility() == View.VISIBLE){
            v = text_share_layout;
        }

        if (v == null){
            return null;
        }

        int w = v.getWidth();
        int h = v.getHeight();
        Log.e("TAG", "width: " + w + " height: " + h);
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        //如果不设置canvas画布为白色，则生成透明

        //v.layout(v.getLeft(), v.getTop(), w, h);
        v.draw(c);

        return bmp;
    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //以下是分享相关的
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    //分享到微信
    private void shareToWX(int type, String title){

        if (shareImg == false){
            WXTextObject textObject = new WXTextObject();
            textObject.text = title;

            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = textObject;
            msg.description = title;

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("text");
            req.message = msg;
            req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
            CustomApplication.mWxApi.sendReq(req);
            return;
        }

        final Bitmap b = viewConversionBitmap();
        if (b == null){
            return;
        }

        final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M

        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.description = CommonUtils.formatString(title);
        msg.title = CommonUtils.formatString(title);
        //设置缩略图
        Bitmap thumbBmp = CommonUtils.getZoomImage(bitmap,24);//最大32k
        msg.thumbData = CommonUtils.bitmapToBytes(thumbBmp);//Util.bmpToByteArray(thumbBmp, true);
        bitmap.recycle();

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            //Log.e("TAG","分享成功");
            uploadShareResult();
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type,String title){

        if (shareImg == false){
            params = new Bundle();
            if (type == 0){//分享给QQ好友
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "微句-言微句美，发现共鸣");// 摘要
                //params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                if(langInfoModel.getImglist() != null && langInfoModel.getImglist().size() > 0){
                    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,langInfoModel.getImglist().get(0));// 网络图片地址
                }else {
                    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
                }
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(ShareActivity.this, params, mIUiListener);
                    }
                });
            }else if(type == 1){
                //分享到QQ空间
                params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
                params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,  "微句-言微句美，发现共鸣");// 摘要
                //params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                ArrayList<String> imgUrlList = new ArrayList<>();
                if(langInfoModel.getImglist() != null && langInfoModel.getImglist().size() > 0){
                    imgUrlList.add(langInfoModel.getImglist().get(0));
                }else {
                    imgUrlList.add("http://image.daydayrise.net/360@2x.png");
                }
                params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQzone(ShareActivity.this, params, mIUiListener);
                    }
                });
            }
            return;
        }

        final Bitmap b = viewConversionBitmap();
        if (b == null){
            return;
        }

        final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M

        String localPath = CommonUtils.getSaveBmp2Gallery(bitmap, System.currentTimeMillis()+"");
        params = new Bundle();
        if (type == 0){//分享给QQ好友

            if (!CommonUtils.isEmpty(localPath)){
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                //params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                //params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                //params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(ShareActivity.this, params, mIUiListener);
                        //CommonUtils.deleteFileByPath(localPath);
                    }
                });
            }

        }else if(type == 1){
            //分享到QQ空间
            if (!CommonUtils.isEmpty(localPath)){

                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                //params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                //params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                //params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(ShareActivity.this, params, mIUiListener);
                        //CommonUtils.deleteFileByPath(localPath);
                    }
                });

//                Tencent tencent = Tencent.createInstance("1105905402", CustomApplication.mContext); //要向腾讯平台申请appid
//                Bundle bundle = new Bundle();
//                bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); //注意，要向qq空间分享纯图片，只能传这三个参数，不能传其他的
//                bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,localPath); //localImgUrl必须是本地手机图片地址
//                bundle.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
//                tencent.shareToQQ(ShareActivity.this, bundle, mIUiListener);


            }
        }
    }

    private void showShare(){
        onClickBottomMenu(-1);
        final ShareDialog shareDialog = new ShareDialog(ShareActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        shareDialog.friend_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到朋友圈
                shareToWX(0, langInfoModel.getTitle());

            }
        });
        shareDialog.wx_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享给微信好友
                shareToWX(1, langInfoModel.getTitle());

            }
        });
        shareDialog.wb_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();

                if (shareImg == false){
                    //微博
                    CustomApplication.WbShareType = 1;
                    CustomApplication.WbShareSourceId = langInfoModel.getLangid();
                    CustomApplication.WbShareText = langInfoModel.getTitle();
                    Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    return;
                }

                final Bitmap b = viewConversionBitmap();
                if (b == null){
                    return;
                }

                final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M
                if (bitmap != null){
                    CustomApplication.WbShareType = 1;
                    CustomApplication.WbShareSourceId = langInfoModel.getLangid();
                    if (langInfoModel.isOriginal() == true){
                        CustomApplication.WbShareText = "原创微句";
                    }else {
                        CustomApplication.WbShareText = langInfoModel.getTitle();
                    }
                    CustomApplication.wbHasImage = true;
                    CustomApplication.wbShareBitmap = bitmap;
                    Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                }
            }
        });
        shareDialog.qq_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到qq
                shareToQQ(0, langInfoModel.getTitle());

            }
        });
        shareDialog.zone_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //qq空间
                shareToQQ(1, langInfoModel.getTitle());

            }
        });
        shareDialog.show();
    }

    private void uploadShareResult(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("id", langInfoModel.getLangid());
        if (shareImg == true){
            if (isEditTP == true){
                map.put("type","2");
            }else {
                map.put("type","1");
            }
        }
        String url = "miniapp/"+"langappid"+"/sharelanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            count += 1;
                        }else {
                            CustomApplication.showTip(commonModel, ShareActivity.this);
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //底部菜单相关
    private void onClickBottomMenu(int index){
        if (index != selectMenuIndex){
            resetMenu();
            shareimg.setVisibility(View.INVISIBLE);
            selectMenuIndex = index;
            updateSelect();
            if (selectMenuIndex == 0){
                isEditTP = true;
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(300);
                mouldmenu.setVisibility(View.VISIBLE);
                mouldmenu.startAnimation(alphaAnimation);
            }else if (selectMenuIndex == 1){
                isEditTP = true;
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(300);
                tpmenu.setVisibility(View.VISIBLE);
                tpmenu.startAnimation(alphaAnimation);
            }else if (selectMenuIndex == 3){
                isEditTP = true;
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(300);
                pbmenu.setVisibility(View.VISIBLE);
                pbmenu.startAnimation(alphaAnimation);
            }else if (selectMenuIndex == 4){
                isEditTP = true;
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(300);
                colormenu.setVisibility(View.VISIBLE);
                colormenu.startAnimation(alphaAnimation);
            }else if (selectMenuIndex == 5){
                isEditTP = true;
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(300);
                symenu.setVisibility(View.VISIBLE);
                symenu.startAnimation(alphaAnimation);
            }else {
                shareimg.setVisibility(View.VISIBLE);
            }
        }else {
            shareimg.setVisibility(View.VISIBLE);
            resetMenu();
            if (selectMenuIndex == 0){
                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimation.setDuration(300);
                mouldmenu.startAnimation(alphaAnimation);
                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mouldmenu.setAlpha(1.0f);
                        mouldmenu.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }else if (selectMenuIndex == 1){
                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimation.setDuration(300);
                tpmenu.startAnimation(alphaAnimation);
                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        tpmenu.setAlpha(1.0f);
                        tpmenu.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }else if (selectMenuIndex == 3){
                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimation.setDuration(300);
                pbmenu.startAnimation(alphaAnimation);
                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        pbmenu.setAlpha(1.0f);
                        pbmenu.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }else if (selectMenuIndex == 4){
                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimation.setDuration(300);
                colormenu.startAnimation(alphaAnimation);
                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        colormenu.setAlpha(1.0f);
                        colormenu.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }else if (selectMenuIndex == 5){
                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimation.setDuration(300);
                symenu.startAnimation(alphaAnimation);
                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        symenu.setAlpha(1.0f);
                        symenu.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            selectMenuIndex = -1;
        }
    }

    private void resetMenu(){
        if (selectMenuIndex == 0){
            //mouldmenu.setAlpha(0.0f);
            mouldmenu.setVisibility(View.INVISIBLE);
            icon1.setImageResource(R.drawable.mould);
            text1.setTextColor(Color.parseColor("#757D88"));
        }else if (selectMenuIndex == 1){
            //tpmenu.setAlpha(0.0f);
            tpmenu.setVisibility(View.INVISIBLE);
            icon2.setImageResource(R.drawable.tupian);
            text2.setTextColor(Color.parseColor("#757D88"));
        }else if (selectMenuIndex == 2){
            /*
            icon3.setImageResource(R.drawable.ziti);
            text3.setTextColor(Color.parseColor("#757D88"));
            */
        }else if (selectMenuIndex == 3){
            //pbmenu.setAlpha(0.0f);
            pbmenu.setVisibility(View.INVISIBLE);
            icon4.setImageResource(R.drawable.align);
            text4.setTextColor(Color.parseColor("#757D88"));
        }else if (selectMenuIndex == 4){
            //colormenu.setAlpha(0.0f);
            colormenu.setVisibility(View.INVISIBLE);
            icon5.setImageResource(R.drawable.yanse);
            text5.setTextColor(Color.parseColor("#757D88"));
        }else if (selectMenuIndex == 5){
            /*
            symenu.setVisibility(View.INVISIBLE);
            icon6.setImageResource(R.drawable.shuiyin);
            text6.setTextColor(Color.parseColor("#757D88"));
            */
        }
    }

    private void updateSelect(){
        if (selectMenuIndex == 0){
            icon1.setImageResource(R.drawable.mouldselect);
            text1.setTextColor(Color.parseColor("#99cc00"));
        }else if (selectMenuIndex == 1){
            icon2.setImageResource(R.drawable.tupianselect);
            text2.setTextColor(Color.parseColor("#99cc00"));
        }else if (selectMenuIndex == 2){
            /*
            icon3.setImageResource(R.drawable.zitiselect);
            text3.setTextColor(Color.parseColor("#99cc00"));
            */
        }else if (selectMenuIndex == 3){
            icon4.setImageResource(R.drawable.alignselect);
            text4.setTextColor(Color.parseColor("#99cc00"));
        }else if (selectMenuIndex == 4){
            icon5.setImageResource(R.drawable.yanseselect);
            text5.setTextColor(Color.parseColor("#99cc00"));
        }else if (selectMenuIndex == 5){
            /*
            icon6.setImageResource(R.drawable.shuiyinselect);
            text6.setTextColor(Color.parseColor("#99cc00"));
            */
        }
    }

    //模板菜单
    private void clickMouldMenu(int index){
        mouldselect1.setVisibility(View.INVISIBLE);
        mouldselect2.setVisibility(View.INVISIBLE);
        mouldselect3.setVisibility(View.INVISIBLE);
        mouldselect4.setVisibility(View.INVISIBLE);
        mouldselect5.setVisibility(View.INVISIBLE);

        writer_layout.setVisibility(View.GONE);
        writer_nickname.setVisibility(View.INVISIBLE);
        writer_header.setVisibility(View.INVISIBLE);
        whitebg.setVisibility(View.INVISIBLE);

        selectMouldIndex = index;
        if (selectMouldIndex == 0){//各个模板加多一层包起来，设置为gone：1
            scrollview1.setVisibility(View.VISIBLE);
            scrollview2.setVisibility(View.GONE);
            scrollview3.setVisibility(View.GONE);
            header.setVisibility(View.GONE);
            cover.setVisibility(View.VISIBLE);
            mouldselect1.setVisibility(View.VISIBLE);
        }else if (selectMouldIndex == 1){//各个模板加多一层包起来：1
            scrollview1.setVisibility(View.VISIBLE);
            scrollview2.setVisibility(View.GONE);
            scrollview3.setVisibility(View.GONE);
            header.setVisibility(View.VISIBLE);
            cover.setVisibility(View.GONE);
            mouldselect2.setVisibility(View.VISIBLE);
        }else if (selectMouldIndex == 2){//各个模板加多一层包起来：2
            scrollview1.setVisibility(View.GONE);
            scrollview2.setVisibility(View.VISIBLE);
            scrollview3.setVisibility(View.GONE);
            mouldselect3.setVisibility(View.VISIBLE);
        }else if (selectMouldIndex == 3){//各个模板加多一层包起来：3
            scrollview1.setVisibility(View.GONE);
            scrollview2.setVisibility(View.GONE);
            scrollview3.setVisibility(View.VISIBLE);
            mouldselect4.setVisibility(View.VISIBLE);
        }else if(selectMouldIndex == 4){
            scrollview1.setVisibility(View.VISIBLE);
            scrollview2.setVisibility(View.GONE);
            scrollview3.setVisibility(View.GONE);
            header.setVisibility(View.GONE);
            cover.setVisibility(View.VISIBLE);
            writer_layout.setVisibility(View.VISIBLE);
            mouldselect5.setVisibility(View.VISIBLE);
            writer_nickname.setVisibility(View.VISIBLE);
            writer_header.setVisibility(View.VISIBLE);
            whitebg.setVisibility(View.VISIBLE);
            whitebg.setBackColor(Color.parseColor(customFontModel.getBgColor()), 20.0f);
        }

    }

    //图片菜单
    private void bindTPMenu(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(10, 0, 0, 0);

        LinearLayout.LayoutParams lps = new LinearLayout.LayoutParams(DisplayUtils.dp2px(ShareActivity.this, 30),
                DisplayUtils.dp2px(ShareActivity.this, 30));
        lps.gravity = Gravity.CENTER;
        lps.setMargins(10, 0, 0, 0);

        for (int i = 0; i < tpmenus.length; i++)
        {
            if (i == 0){
               ImageView imageView = new ImageView(this);
               imageView.setImageResource(R.drawable.xiangce);
               imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
               imageView.setAdjustViewBounds(true);
               imageView.setLayoutParams(lps);
               imageView.setTag(i);
               imageView.setClickable(true);
               imageView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       clickPicMenu(view);
                   }
               });
               tpItemContainer.addView(imageView);
            }else if (i == 1){
                ImageView imageView = new ImageView(this);
                imageView.setImageResource(R.drawable.paizhao);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setAdjustViewBounds(true);
                imageView.setLayoutParams(lps);
                imageView.setTag(i);
                imageView.setClickable(true);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clickPicMenu(view);
                    }
                });
                tpItemContainer.addView(imageView);
            }else {
                TextView textView = new TextView(this);
                textView.setText(tpmenus[i]);
                textView.setTextSize((int) DisplayUtils.px2sp(ShareActivity.this, DisplayUtils.sp2px(ShareActivity.this, 14)));
                textView.setPadding(10, 5, 5, 5);
                if (i == tpmenus.length - 1){
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.gravity = Gravity.CENTER;
                    lp.setMargins(10, 0, 10, 0);
                    textView.setLayoutParams(lp);
                }else {
                    textView.setLayoutParams(layoutParams);
                }
                if (i == selectTPIndex){
                    textView.setBackgroundResource(R.drawable.menu_select_bg);
                    textView.setTextColor(Color.parseColor("#99cc00"));
                    selectTPTextView = textView;
                }else {
                    textView.setBackgroundResource(R.drawable.menu_normal_bg);
                    textView.setTextColor(Color.parseColor("#434A54"));
                }
                textView.setTag(i);
                textView.setClickable(true);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clickPicMenu(view);
                    }
                });
                if (tpmenus[i].equals("原图")){
                    originalTPTextView = textView;
                }
                tpItemContainer.addView(textView);
            }
            tpItemContainer.invalidate();
        }
    }

    private void clickPicMenu(View view){
        int index = (int)view.getTag();
        if (index > 1 && index != selectTPIndex){
            selectTPTextView.setBackgroundResource(R.drawable.menu_normal_bg);
            selectTPTextView.setTextColor(Color.parseColor("#434A54"));

            selectTPTextView = (TextView)view;
            selectTPTextView.setBackgroundResource(R.drawable.menu_select_bg);
            selectTPTextView.setTextColor(Color.parseColor("#99cc00"));

            selectTPIndex = index;
            String selectStr = tpmenus[selectTPIndex];
            if (selectStr.equals("原图")) {
                isOriginalTP = true;
            }else {
                isOriginalTP = false;
            }

            updateImageView();

        }else if (index == 0){
            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//关闭滤镜
                PermissionUtils.isPictureNote(ShareActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                if (ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                                    ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                            MainActivity.REQUEST_PERMISSION);
                                    return;
                                }
                            }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                    && ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                        REQUEST_PERMISSION);
                                //ToastUtil.show(ShareActivity.this,"亲，请开启应用对SD卡的读写权限");
                                return;
                            }
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                                startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                                return;
                            }
                            MultiImageSelector.create()
                                    .showCamera(false)
                                    .count(1)
                                    .multi()
                                    .start(ShareActivity.this, REQUEST_PUBLISH);
                        }
                    }
                });
            }else {
                doPickPhotoFromGallery();
            }
        }else if (index == 1){
            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//关闭滤镜
                doTakePhoto();
            }else {
                takeOnePhoto();
            }
        }
    }

    private void updateImageView(){
        float scale = getTPScale();
        int height = Math.round(screenWidth * scale);
        ViewGroup.LayoutParams params = cover.getLayoutParams();
        params.height = height;
        cover.setLayoutParams(params);
        params = down_cover.getLayoutParams();
        params.height = height;
        down_cover.setLayoutParams(params);

        String selectStr = tpmenus[selectTPIndex];
        if (selectStr.equals("原图")){
            if (originalBitmap != null){
                Glide.with(ShareActivity.this).load(originalBitmap).transform(new CircleTransform(ShareActivity.this)).dontAnimate().into(header);
                cover.setScaleType(ImageView.ScaleType.FIT_XY);
                cover.setImageBitmap(originalBitmap);
                down_cover.setScaleType(ImageView.ScaleType.FIT_XY);
                down_cover.setImageBitmap(originalBitmap);
            }
        }else {
            cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
            down_cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
            if (selectBitmap != null){
                cover.setImageBitmap(selectBitmap);
                down_cover.setImageBitmap(selectBitmap);
                Glide.with(ShareActivity.this).load(selectBitmap).transform(new CircleTransform(ShareActivity.this)).dontAnimate().into(header);
            }else {
                try{
                    Glide.with(ShareActivity.this).load(imgUrl).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
                }
                try{
                    Glide.with(ShareActivity.this).load(imgUrl).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(down_cover);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
                }
                try{
                    //diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
                    Glide.with(ShareActivity.this).load(imgUrl).transform(new CircleTransform(ShareActivity.this)).dontAnimate().into(header);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
                }
            }
        }

    }

    private float getTPScale(){

        String selectStr = tpmenus[selectTPIndex];
        if (selectStr.equals("原图")){
            return bitmapScale;
        }else if (selectStr.equals("30:17")){
            return 17.0f/30.0f;
        }else if (selectStr.equals( "1:1")){
            return 1.0f;
        }else if (selectStr.equals("2:1")){
            return 1.0f/2.0f;
        }else if (selectStr.equals("16:9")){
            return 9.0f/16.0f;
        }else if (selectStr.equals("4:3")){
            return 3.0f/4.0f;
        }else if (selectStr.equals("2:3")){
            return 3.0f/2.0f;
        }else if (selectStr.equals("3:2")){
            return 2.0f/3.0f;
        }else if (selectStr.equals("3:4")){
            return 4.0f/3.0f;
        }

        return 17.0f/30.0f;
    }

    private void showImageMenu(){

        onClickBottomMenu(-1);
        List<String> itemList = new ArrayList<String>();
        itemList.add("拍一张");
        itemList.add("从相册选择");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ShareActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : itemList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        if (which == 1){
                            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//关闭滤镜
                                doTakePhoto();
                            }else {
                                takeOnePhoto();
                            }
                        }else if (which == 2){
                            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//关闭滤镜
                                PermissionUtils.isPictureNote(ShareActivity.this, new PermissionCallback() {
                                    @Override
                                    public void onResult(boolean flag, boolean showAlert) {
                                        if (flag == true){
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                                if (ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                                                    ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                                            MainActivity.REQUEST_PERMISSION);
                                                    return;
                                                }
                                            }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                                    && ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                                ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                        REQUEST_PERMISSION);
                                                //ToastUtil.show(ShareActivity.this,"亲，请开启应用对SD卡的读写权限");
                                                return;
                                            }
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                                                startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                                                return;
                                            }
                                            MultiImageSelector.create()
                                                    .showCamera(false)
                                                    .count(1)
                                                    .multi()
                                                    .start(ShareActivity.this, REQUEST_PUBLISH);

                                        }
                                    }
                                });

                            }else {
                                doPickPhotoFromGallery();
                            }

                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }


    /**拍照获取相片**/
    private void doTakePhoto() {
        PermissionUtils.showCamaraNote(ShareActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        imageFileName = System.currentTimeMillis() + Constant.weijuTakePhoto;
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(ShareActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });

    }

    /**拍照获取相片**/
    private void takeOnePhoto() {
        PermissionUtils.showCamaraNote(ShareActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(ShareActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });

    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限被用户同意，可以做你要做的事情了。
            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                    startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                    return;
                }
                MultiImageSelector.create()
                        .showCamera(false)
                        .count(1)
                        .multi()
                        .start(ShareActivity.this, REQUEST_PUBLISH);
            }else {
                doPickPhotoFromGallery();
            }

        } else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            CustomDialog dialog = null;
            final CustomDialog.Builder builder = new CustomDialog.Builder(ShareActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("应用需要开启相机权限，是否去设置？");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //跳转App设置权限的界面
                    Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                    String pkg = "com.android.settings";
                    String cls = "com.android.settings.applications.InstalledAppDetails";
                    i.setComponent(new ComponentName(pkg, cls));
                    i.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(i);
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            dialog.show();

        }
    }

    //------------------图片相关-----------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
                return;
            }
        }

        if (requestCode == REQUEST_PUBLISH && resultCode == RESULT_OK) {//从相册选择完图片
            if (data == null){
                return;
            }
            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                List<String> imgList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (imgList != null && imgList.size() > 0){
                    String uri = imgList.get(0);
                    if (uri.contains(Constant.weijuTakePhoto) == true){
                        Bitmap bitmap = ImageUtils.getBitmap(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),uri));
                        if (bitmap == null){
                            bitmap = ImageUtils.getBitmap(uri);
                        }
                        selectBitmap = bitmap;
                    }else {
                        Bitmap bitmap = ImageUtils.getBitmap(uri);
                        selectBitmap = bitmap;
                    }
                    if (selectBitmap != null){
                        originalBitmap = selectBitmap;
                        int width = originalBitmap.getWidth();
                        int height = originalBitmap.getHeight();
                        bitmapScale = 1.0f*height/width;
                        updateImageView();
                    }

                }
            }else {
                try{
                    Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0)));
                    if (imageUri == null){
                        return;
                    }
                    cropImage(imageUri);
                }catch (Exception e){
                    ToastUtil.show(ShareActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                    LangPublishActivity.uploadError("微句选择封面报错："+e.getLocalizedMessage());
                }

            }
        }else if(requestCode == PHOTO_PICKER_REQUEST_CODE && resultCode == RESULT_OK){//android 13
            if (data != null){
                cropSelectImage(data.getData());
            }
        }else if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){

            try {
                Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                if (imageUri == null){
                    ToastUtil.show(ShareActivity.this,"没有图片");
                    return;
                }
                cropSelectImage(imageUri);
            }catch (Exception e){
                ToastUtil.show(ShareActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                LangPublishActivity.uploadError("微句拍照封面报错："+e.getLocalizedMessage());
            }

            /*
            if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ){

                String uri = imageFileName;
                if (uri.contains(Constant.weijuTakePhoto) == true){
                    Bitmap bitmap = ImageUtils.getBitmap(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),uri));
                    if (bitmap == null){
                        bitmap = ImageUtils.getBitmap(uri);
                    }
                    selectBitmap = bitmap;
                }else {
                    Bitmap bitmap = ImageUtils.getBitmap(uri);
                    selectBitmap = bitmap;
                }
                if (selectBitmap != null){
                    originalBitmap = selectBitmap;
                    int width = originalBitmap.getWidth();
                    int height = originalBitmap.getHeight();
                    bitmapScale = 1.0f*height/width;
                    updateImageView();
                }

            }else {
                try {
                    Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                    if (imageUri == null){
                        ToastUtil.show(ShareActivity.this,"没有图片");
                        return;
                    }
                    cropSelectImage(imageUri);
                }catch (Exception e){
                    ToastUtil.show(ShareActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                    LangPublishActivity.uploadError("微句拍照封面报错："+e.getLocalizedMessage());
                }

            }
            */

        }else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            try {
                final Uri resultUri = UCrop.getOutput(data);
                Bitmap bmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                if (bmap != null){
                    originalBitmap = bmap;
                    selectBitmap = bmap;
                    int width = originalBitmap.getWidth();
                    int height = originalBitmap.getHeight();
                    bitmapScale = 1.0f*height/width;
                    updateImageView();
                }
            }catch (Exception e){
                ToastUtil.show(ShareActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                LangPublishActivity.uploadError("微句裁剪封面报错："+e.getLocalizedMessage());
            }

        }else if (requestCode == CHOOSE_PICTURE && resultCode == RESULT_OK){//从相册选择一张进行裁剪
            if (data != null){

                ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (resultPhotos != null && resultPhotos.size() > 0){
                    Photo photo = resultPhotos.get(0);
                    try{
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(photo.path));
                        if (imageUri == null){
                            return;
                        }
                        cropSelectImage(imageUri);
                    }catch (Exception e){
                        ToastUtil.show(ShareActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                        LangPublishActivity.uploadError("微句选择封面报错："+e.getLocalizedMessage());
                    }


                }

            }
        }
    }

    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        PermissionUtils.isPictureNote(ShareActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                        startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                        return;
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(ShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(ShareActivity.this,"亲，请开启应用对SD卡的读写权限");
                        return;
                    }

                    EasyPhotos.createAlbum(ShareActivity.this, false, GlideEngine.getInstance())
                            .start(CHOOSE_PICTURE);
                }
            }
        });

    }

    //裁剪
    private void cropImage(Uri uri){

        int x = 30;
        int y = 17;
        if (selectMouldIndex == 1){
            x = 1;
            y = 1;
        }else {

            String selectStr = tpmenus[selectTPIndex];
            if (selectStr.equals("30:17")){
                x = 30;
                y = 17;
            }else if (selectStr.equals( "1:1")){
                x = 1;
                y = 1;
            }else if (selectStr.equals("2:1")){
                x = 2;
                y = 1;
            }else if (selectStr.equals("16:9")){
                x = 16;
                y = 9;
            }else if (selectStr.equals("4:3")){
                x = 4;
                y = 3;
            }else if (selectStr.equals("2:3")){
                x = 2;
                y = 3;
            }else if (selectStr.equals("3:2")){
                x = 3;
                y = 2;
            }else if (selectStr.equals("3:4")){
                x = 3;
                y = 4;
            }

        }

        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto));
        float density = ScreenUtils.getScreenDensity(ShareActivity.this);
        UCrop.of(uri, imageUri)//"imageout.jpg"
                .withAspectRatio(x, y)
                .withMaxResultSize((int)(1920*density), (int)(1920*density))
                .start(ShareActivity.this);

    }

    //裁剪
    private void cropSelectImage(Uri uri){

        int x = 30;
        int y = 17;
        if (selectMouldIndex == 1){
            x = 1;
            y = 1;
        }else {
            String selectStr = tpmenus[selectTPIndex];
            if (selectStr.equals("30:17")){
                x = 30;
                y = 17;
            }else if (selectStr.equals( "1:1")){
                x = 1;
                y = 1;
            }else if (selectStr.equals("2:1")){
                x = 2;
                y = 1;
            }else if (selectStr.equals("16:9")){
                x = 16;
                y = 9;
            }else if (selectStr.equals("4:3")){
                x = 4;
                y = 3;
            }else if (selectStr.equals("2:3")){
                x = 2;
                y = 3;
            }else if (selectStr.equals("3:2")){
                x = 3;
                y = 2;
            }else if (selectStr.equals("3:4")){
                x = 3;
                y = 4;
            }
        }

        float density = ScreenUtils.getScreenDensity(ShareActivity.this);
        if (isOriginalTP == true || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ){
            UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto)))//"imageout.jpg"
                    .useSourceImageAspectRatio()
                    .withMaxResultSize((int)(1920*density), (int)(1920*density))
                    .start(ShareActivity.this);
            return;
        }
        UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto)))//"imageout.jpg"
                .withAspectRatio(x, y)
                .withMaxResultSize((int)(1920*density), (int)(1920*density))
                .start(ShareActivity.this);
    }


    //排版菜单
    private void bindPBMenu(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(10, 0, 0, 0);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DisplayUtils.dp2px(ShareActivity.this, 30),
                DisplayUtils.dp2px(ShareActivity.this, 30));
        lp.gravity = Gravity.CENTER;
        lp.setMargins(10, 0, 0, 0);

        int i = 0;
        for (; i < pbmenus.length; i++){
            TextView textView = new TextView(this);
            textView.setText(pbmenus[i]);
            textView.setTextSize((int) DisplayUtils.px2sp(ShareActivity.this, DisplayUtils.sp2px(ShareActivity.this, 14)));
            textView.setPadding(10, 5, 10, 5);
            textView.setLayoutParams(layoutParams);
            textView.setBackgroundResource(R.drawable.menu_normal_bg);
            textView.setTextColor(Color.parseColor("#434A54"));
            textView.setTag(i);
            textView.setClickable(true);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickPBMenu(view);
                }
            });
            pbItemContainer.addView(textView);
            pbItemContainer.invalidate();
        }

        for ( ;i < pbiconmenus.length + pbmenus.length; i++)
        {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(pbiconmenus[i-pbmenus.length]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setAdjustViewBounds(true);
            if (i == pbiconmenus.length + pbmenus.length - 1){
                LinearLayout.LayoutParams lps = new LinearLayout.LayoutParams(DisplayUtils.dp2px(ShareActivity.this, 30),
                        DisplayUtils.dp2px(ShareActivity.this, 30));
                lps.gravity = Gravity.CENTER;
                lps.setMargins(10, 0, 10, 0);
                imageView.setLayoutParams(lps);
            }else {
                imageView.setLayoutParams(lp);
            }
            imageView.setTag(i);
            imageView.setClickable(true);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickPBMenu(view);
                }
            });
            pbItemContainer.addView(imageView);
            pbItemContainer.invalidate();
        }
    }

    private void clickPBMenu(View view){
        int index = (int) view.getTag();
        if (index == 0){//A+
            customFontModel.setFontSize(customFontModel.getFontSize()+1);
            if (customFontModel.getFontSize() > 100){
                customFontModel.setFontSize(100);
            }
        }else if (index == 1){//A-
            if (customFontModel.getFontSize() > 10){
                customFontModel.setFontSize(customFontModel.getFontSize()-1);
            }
        }else if (index == 2){//标准
            customFontModel.setFontSize(16);
        }else if (index == 3){//小
            customFontModel.setFontSize(13);
        }else if (index == 4){//中
            customFontModel.setFontSize(20);
        }else if (index == 5){//大
            customFontModel.setFontSize(40);
        }else if (index == 6){//左对齐
            customFontModel.setGravity(Gravity.LEFT);
        }else if (index == 7){//居中对齐
            customFontModel.setGravity(Gravity.CENTER);
        }else if (index == 8){//右对齐
            customFontModel.setGravity(Gravity.RIGHT);
        }else if (index == 9){//两端对齐
            customFontModel.setGravity(Gravity.NO_GRAVITY);
        }else if (index == 10){//加大间距
            customFontModel.setPadding(customFontModel.getPadding()+2);
        }else if(index == 11){//减少间距
            if (customFontModel.getPadding() > 1){
                customFontModel.setPadding(customFontModel.getPadding()-2);
            }
        }

        /*
        setLineSpacing()原型为public void setLineSpacing(float add, float mult);
        参数add：增加的间距数值，对应android:lineSpacingExtra参数。
        参数mult：增加的间距倍数，对应android:lineSpacingMultiplier参数。
        最终结果：原行间距 x mult+add
        */

        updateTextView();
    }

    private void updateTextView(){
        text.setGravity(customFontModel.getGravity());
        text.setTextSize((int) DisplayUtils.px2sp(ShareActivity.this, DisplayUtils.sp2px(ShareActivity.this, customFontModel.getFontSize())));
        text.setPadding(DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()), DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()));
        text.setTextColor(Color.parseColor(customFontModel.getFontColor()));
        if (writer_nickname != null){
            writer_nickname.setTextColor(Color.parseColor(customFontModel.getFontColor()));
        }
        if (whitebg != null){
            whitebg.setBackColor(Color.parseColor(customFontModel.getBgColor()), 20.0f);
        }

        up_text.setGravity(customFontModel.getGravity());
        up_text.setTextSize((int) DisplayUtils.px2sp(ShareActivity.this, DisplayUtils.sp2px(ShareActivity.this, customFontModel.getFontSize())));
        up_text.setPadding(DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()), DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()));
        up_text.setTextColor(Color.parseColor(customFontModel.getFontColor()));

        full_text.setGravity(customFontModel.getGravity());
        full_text.setTextSize((int) DisplayUtils.px2sp(ShareActivity.this, DisplayUtils.sp2px(ShareActivity.this, customFontModel.getFontSize())));
        full_text.setPadding(DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()), DisplayUtils.dp2px(ShareActivity.this, 15), DisplayUtils.dp2px(ShareActivity.this, customFontModel.getPadding()));
        full_text.setTextColor(Color.parseColor(customFontModel.getFontColor()));

        from.setTextColor(Color.parseColor(customFontModel.getTipColor()));
        from_tip.setTextColor(Color.parseColor(customFontModel.getTipColor()));
        uptext_downimg_from.setTextColor(Color.parseColor(customFontModel.getTipColor()));
        uptext_downimg_from_tip.setTextColor(Color.parseColor(customFontModel.getTipColor()));
        fulltext_from.setTextColor(Color.parseColor(customFontModel.getTipColor()));
        fulltext_from_tip.setTextColor(Color.parseColor(customFontModel.getTipColor()));

        img_share_layout.setBackgroundColor(Color.parseColor(customFontModel.getBgColor()));
        uptext_downimg_share_layout.setBackgroundColor(Color.parseColor(customFontModel.getBgColor()));
        text_share_layout.setBackgroundColor(Color.parseColor(customFontModel.getBgColor()));
    }

    //颜色菜单
    private void bindTextColorMenu(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DisplayUtils.dp2px(ShareActivity.this, 40),
                DisplayUtils.dp2px(ShareActivity.this, 40));
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(0, 0, 0, 0);

        int i = 0;
        for (; i < colormenus.length; i++){
            TextView textView = new TextView(this);
            textView.setText("");
            textView.setPadding(0, 0, 0, 0);
            textView.setLayoutParams(layoutParams);
            textView.setBackgroundColor(Color.parseColor(colormenus[i]));
            textView.setTag(i);
            textView.setClickable(true);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickTextColorMenu(view);
                }
            });
            textcolorItemContainer.addView(textView);
            textcolorItemContainer.invalidate();
        }
    }

    private void bindBgColorMenu(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DisplayUtils.dp2px(ShareActivity.this, 40),
                DisplayUtils.dp2px(ShareActivity.this, 40));
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(0, 0, 0, 0);

        int i = 0;
        for (; i < colormenus.length; i++){
            TextView textView = new TextView(this);
            textView.setText("");
            textView.setPadding(0, 0, 0, 0);
            textView.setLayoutParams(layoutParams);
            textView.setBackgroundColor(Color.parseColor(colormenus[i]));
            textView.setTag(i);
            textView.setClickable(true);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickBgColorMenu(view);
                }
            });
            bgcolorItemContainer.addView(textView);
            bgcolorItemContainer.invalidate();
        }
    }

    private void clickTextColorMenu(View view){
        int index = (int)view.getTag();
        customFontModel.setFontColor(colormenus[index]);
        updateTextView();
    }

    private void clickBgColorMenu(View view){
        int index = (int)view.getTag();
        customFontModel.setBgColor(colormenus[index]);
        if (customFontModel.getBgColor().contains("808069")
         || customFontModel.getBgColor().contains("292421")
                || customFontModel.getBgColor().contains("FF4500")
                || customFontModel.getBgColor().contains("A020F0")
                || customFontModel.getBgColor().contains("FF00FF")
                || customFontModel.getBgColor().contains("FF6347")
                || customFontModel.getBgColor().contains("B03060")
                || customFontModel.getBgColor().contains("9C661F")
                || customFontModel.getBgColor().contains("E3170D")
                || customFontModel.getBgColor().contains("385E0F")
                || customFontModel.getBgColor().contains("3D59AB")
                || customFontModel.getBgColor().contains("00C78C")
                || customFontModel.getBgColor().contains("FF7F50")
                || customFontModel.getBgColor().contains("872657")
                || customFontModel.getBgColor().contains("B22222")){
            customFontModel.setTipColor("#FFFFFF");
        }else if(customFontModel.getBgColor().contains("C0C0C0")
        || customFontModel.getBgColor().contains("00C957")
        || customFontModel.getBgColor().contains("FFC0CB")){
            customFontModel.setTipColor("#757D88");
        }else {
            customFontModel.setTipColor("#C0C0C0");
        }
        updateTextView();
    }

    //水印菜单
    private void bindSYMenu(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(10, 0, 10, 0);

        for (int i = 0 ;i < symenus.length; i++)
        {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(symenus[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setAdjustViewBounds(true);
            imageView.setLayoutParams(layoutParams);
            imageView.setTag(i);
            imageView.setClickable(true);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickSYMenu(view);
                }
            });
            syItemContainer.addView(imageView);
            syItemContainer.invalidate();
        }
    }

    private void clickSYMenu(View view){
        int index = (int)view.getTag();
        if (index == 0){
            bottom_layout.setVisibility(View.VISIBLE);
            uptext_downimg_bottom_layout.setVisibility(View.VISIBLE);
            fulltext_bottom_layout.setVisibility(View.VISIBLE);
        }else if (index == 1){
            bottom_layout.setVisibility(View.GONE);
            uptext_downimg_bottom_layout.setVisibility(View.GONE);
            fulltext_bottom_layout.setVisibility(View.GONE);
        }
    }

}
